import { ref } from "vue"

interface Path {
    data: string,
    total: string,
    pageSize: string,
    currentPage: string
}
interface Params {
    get?: {
        api?: ((params: any) => any),
        params?: any
    },
    options?: {
        path?: Path,
        immediatly?: boolean,
        isUseFEPaging?: boolean
        pagination?: {
            pageSize?: number,
            currentPage?: number,
        }
    }
}
export const useTable = (params: Params, tes?: any) => {
    const showData = ref<any>()
    const data = ref<any>()
    const totalLength = ref<number>(0)

    const { get = {}, options = {} } = params
    const { api: getAPI } = get
    const { 
        immediatly = true, 
        isUseFEPaging = false, 
        pagination = {}, 
        path = {
            data: 'record',
            total: 'length',
            pageSize: 'size',
            currentPage: 'pageNo'
        } 
    } = options

    const paginationOption = ref<any>({
        pageSize: pagination.pageSize ?? 10,
        currentPage: pagination.currentPage ?? 1,
        totalLength: pagination.currentPage ?? 0,
    })

    const getShowData = () => {
        if (typeof getAPI === 'function') {
            const requestData = {
                [path.pageSize]: paginationOption.value.pageSize,
                [path.currentPage]: paginationOption.value.currentPage,
                ...tes
            }
            // const a = tes ? Object.assign(tes, requestData) : requestData
            getAPI(requestData).then((res: any) => {
                paginationOption.value.totalLength = res.totalLength
                data.value = res.data
                showData.value = res.data
                handleCurrentChange(false)
            })
        }
    }

    const handleCurrentChange = (isClickChangePage: boolean = true) => {
        if (isUseFEPaging) {
            const start = paginationOption.value.pageSize * (paginationOption.value.currentPage - 1);
            showData.value = data.value.slice(start, start + paginationOption.value.pageSize);
        } else {
            if (isClickChangePage) {
                getShowData()
            }
        }
    }

    immediatly && getShowData()

    return {
        showData,
        pagination: paginationOption,
        getShowData,
        handleCurrentChange
    }
}